package org.ligson.springboot.simple.demo;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import org.springframework.util.StringUtils;

import java.io.IOException;

public class ReferenceDeserializer extends JsonDeserializer implements ContextualDeserializer {
    private BeanProperty beanProperty;

    public ReferenceDeserializer(BeanProperty property) {
        this.beanProperty = property;
    }

    public ReferenceDeserializer() {
    }

    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode jsonNode;
        if (jsonParser.getValueAsLong() == 0) {
            jsonNode = jsonParser.readValueAsTree();
        } else {
            //JsonNode jsonNode = jsonParser.readValueAs(JsonNode.class);
            jsonNode = new ObjectMapper().readTree(jsonParser.getText());
        }
        //JsonNode jsonNode = jsonParser.readValueAs(JsonNode.class);
        if (jsonNode.isObject()) {
            JsonNode idNode = jsonNode.get("id");
            if (idNode != null) {
                return idNode.asLong();
            } else {
                return null;
            }
        } else {
            String text = jsonNode.asText();
            if (!StringUtils.isEmpty(text)) {
                return Long.valueOf(text);
            } else {
                return null;
            }
        }
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        return new ReferenceDeserializer(property);
    }
}
